package com.leps.nq.bu.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leps.nq.bu.entity.BuPump;
import com.leps.nq.bu.entity.BuWell;
import com.leps.nq.bu.mapper.BuPumpMapper;
import com.leps.nq.bu.mapper.BuWellMapper;
import com.leps.nq.bu.service.IBuPumpService;
import com.leps.nq.bu.vo.PumpQueryModel;
import com.leps.nq.bu.vo.PumpVo;
import com.leps.nq.common.util.SecurityUtil;
import com.leps.nq.common.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 泵表 服务实现类
 * </p>
 *
 * @author hex
 * @since 2022-05-22
 */
@Service
public class BuPumpServiceImpl extends ServiceImpl<BuPumpMapper, BuPump> implements IBuPumpService {

    @Autowired
    private BuPumpMapper pumpMapper;
    @Autowired
    private BuWellMapper wellMapper;

    @Override
    public PageVo<PumpVo> pageByQueryModel(PumpQueryModel queryModel) {
        Page<PumpVo> page = Page.of(queryModel.getPageNum(), queryModel.getPageSize());
        page = this.pumpMapper.selectByQueryModel(page, queryModel);
        return PageVo.of(page);
    }

    @Override
    public boolean updateCascade(BuPump pump) {
        final int pumpId = pump.getPumpId();
        final String pumpName = pump.getPumpName();
        final String origin = this.pumpMapper.selectById(pumpId).getPumpName();
        pump.setUpdateBy(SecurityUtil.getUserName());
        pump.setUpdateTime(new Date());
        this.pumpMapper.updateById(pump);
        this.pumpMapper.updateRedundantField(pump);
        if(Objects.equals(origin, pumpName)) return true;
        BuWell well = new BuWell();
        well.setPumpName(pumpName);
        this.wellMapper.update(well, new UpdateWrapper<BuWell>().eq("pump_id", pumpId));
        return true;
    }

    @Override
    public void updateRundantField(BuPump pump) {
        this.pumpMapper.updateRedundantField(pump);
    }
}
